package com.psa.component;

import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.psa.adapter.IJsonDataItemViewCreator;
import com.wxw.BaseLibrary.element.JsonObject;
import com.wxw.BaseLibrary.element.JsonProperty;
import com.psa.adapter.JsonDataAdapter;

/**
 * @author david
 */
public class DefaultItemViewCreator implements IJsonDataItemViewCreator {
    private JsonProperty jsonDataList;
    private JsonProperty jsonSetting;
    private int layoutId;

    public DefaultItemViewCreator(int layoutId, JsonProperty jsonData, JsonProperty jsonSetting) {
        this.layoutId = layoutId;
        this.jsonDataList = jsonData;
        this.jsonSetting = jsonSetting;
    }

    @Override
    public View createView(int position, View convertView, LayoutInflater inflater, JsonObject jsonData) {
        ViewsHelper viewsHelper = null;
        JsonObject jsonObject = jsonDataList.get(position).getObject();
        if (convertView == null){
            convertView = inflater.inflate(layoutId, null);
            viewsHelper = new ViewsHelper();
            for (JsonProperty jsonProperty : jsonSetting.getItems()) {
                viewsHelper.getViewMap().put(jsonProperty.getProperty("key").getValue(),
                        convertView.findViewById(jsonProperty.getProperty("id").getInteger()));
            }
            convertView.setTag(viewsHelper);
        } else {
            viewsHelper = (ViewsHelper)convertView.getTag();
        }
        for (JsonProperty jsonProperty : jsonSetting.getItems()) {
            if (jsonProperty.getProperty("set").getBoolean()) {
                setValue(viewsHelper, jsonProperty.getProperty("key").getValue(),
                        jsonProperty.getProperty("label").getValue(), jsonObject);
            }
        }

        for (JsonProperty jsonProperty : jsonSetting.getItems()) {
            if (jsonProperty.getProperty(JsonDataAdapter.SHOW).getBoolean()) {
                String key = jsonProperty.getProperty(JsonDataAdapter.KEY).getValue();
                if (jsonObject.getProperty(key) == null
                        || jsonObject.getProperty(key).getValue().equals("")
                        || jsonObject.getProperty(key).getValue().equals("null")) {
                    viewsHelper.getViewMap().get(key).setVisibility(View.INVISIBLE);
                } else {
                    viewsHelper.getViewMap().get(key).setVisibility(View.VISIBLE);
                }
            }
        }

        return convertView;
    }

    protected void setValue(ViewsHelper viewsHelper, String key, String label, JsonObject jsonObject) {
        ((TextView)viewsHelper.getViewMap().get(key)).setText(label + jsonObject.getProperty(key).getValue());
    }
}
